package com.jlwl.houseservice.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jlwl.houseservice.entity.Administrator;
import com.jlwl.houseservice.entity.User;
import com.jlwl.houseservice.mapper.AdministratorMapper;
import com.jlwl.houseservice.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 用户详情服务实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final AdministratorMapper administratorMapper;

    private final UserMapper userMapper;

    public UserDetailsServiceImpl(AdministratorMapper administratorMapper, UserMapper userMapper) {
        this.administratorMapper = administratorMapper;
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 先查找管理员
        Administrator admin = administratorMapper.selectOne(
                new LambdaQueryWrapper<Administrator>().eq(Administrator::getUsername, username)
        );

        if (admin != null) {
            Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            return new org.springframework.security.core.userdetails.User(
                    admin.getUsername(),
                    admin.getPassword(),
                    authorities
            );
        }

        // 再查找普通用户
        User user = userMapper.selectOne(
                new LambdaQueryWrapper<User>().eq(User::getPhone, username)
        );

        if (user != null) {
            Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            return new org.springframework.security.core.userdetails.User(
                    user.getPhone(),
                    user.getPassword(),
                    authorities
            );
        }

        throw new UsernameNotFoundException("用户名或密码错误");
    }
}